package org.elanfox.intellicommunity.common.utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author wm
 */
public class SignBuilderUtils {

    private final static Logger logger = LoggerFactory.getLogger(SignBuilderUtils.class);

    /**
     * 创建一个sign签名
     * 忽略值为空的
     *
     * @param params 代签名参数，key排序的map
     * @param prefix 签名前缀
     * @param suffix 签名后缀
     * @return 返回鉴权信息字符串
     */
    public static String buildSignIgnoreEmpty(Map<String, String> params, String prefix, String suffix) throws UnsupportedEncodingException {
        if (prefix == null) {
            prefix = "";
        }
        if (suffix == null) {
            suffix = "";
        }
        //先对map中的参数进行排序
        List arrayList = new ArrayList(params.entrySet());
        Collections.sort(
                arrayList, (arg1, arg2) -> {
                    Map.Entry obj1 = (Map.Entry) arg1;
                    Map.Entry obj2 = (Map.Entry) arg2;
                    return (obj1.getKey()).toString().compareTo(
                            (String) obj2.getKey()
                    );
                }
        );
        //对所有参数进行拼接key + value
        StringBuilder stringBuilder = new StringBuilder(prefix);
        for (Object anArrayList : arrayList) {
            Map.Entry entry = (Map.Entry) anArrayList;
            if (StringUtils.isEmpty(entry.getValue())) {
                continue;
            }
            String key = (String) entry.getKey();
//            stringBuilder.append(key.toLowerCase());
            stringBuilder.append(key);
            stringBuilder.append(entry.getValue());
        }
        stringBuilder.append(suffix);
        return DigestUtils.md5Hex(stringBuilder.toString().getBytes("UTF-8"));
    }
}
